//
//  OAuthViewController.swift
//  WBTest
//
//  Created by 张海峰 on 2017/7/25.
//  Copyright © 2017年 张海峰. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
  //MARK:-   控件的属性
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        loadpage()
        }
}
  //MARK:-   设置UI相关
extension OAuthViewController{
    func setupNavigationBar(){
    //左
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", style: .plain, target: self, action: #selector(closeItemClick))
    //右
         navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "填充", style: .plain, target: self, action: #selector(fillItemClick))
    }
    func loadpage(){
        webView.loadRequest(URLRequest.init(url: URL.init(string: "https://www.i-fbs.com/index.php?app=member&act=login")!))
    }
}
//MARK:-  webView的delegate方法
extension OAuthViewController:UIWebViewDelegate{
    
    //webView 开始加载网页
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //webView 网页加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //webView加载网页失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
         SVProgressHUD.dismiss()
    }
    //webView加载页面时先访问这个方法true加载 false 不加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       //获取加载网页的NSURL
        guard let url = request.url else {
            return true
        }
        
        //2. 获取url中的字符串
        let urlStr = url.absoluteString
       //  print("urlStr"+urlStr)
        //3. 判断urlStr 是否包含code
        guard urlStr.contains("code=") else {
            return true
        }
       
        //4. 将code取出来
        let code = urlStr.components(separatedBy: "code=")
       
        return false
        
        
    }

}
//MARK:-   点击事件
extension OAuthViewController{
    func closeItemClick(){
        dismiss(animated: true, completion: nil)
    }
    func fillItemClick(){
        // 书写js代码 ：javascript / java
        let jsCode = "document.getElementById('user_name').value ='neillo@a-rtimax.com';document.getElementById('password').value ='artimax11mar';"
        //执行js代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
        print("填充")
        //需要登录，把用户信息存储起来。
        //把user对象保存
        let user = UserInfo(dict:["name" : "why","age" : "18" ,"weight" : "50.8"])
        NSKeyedArchiver.archiveRootObject(user, toFile: UserInfoViewModel.shareInstance.userPath)
        //填充之后成功进入欢迎界面
        dismiss(animated: false) { 
            UIApplication.shared.keyWindow?.rootViewController =  WelcomeViewController()
        }
    }
}
